// src/store/slice/searchKey.ts
import { createEntityAdapter, createSlice, Draft, EntityState, nanoid, PayloadAction } from "@reduxjs/toolkit";
import { AppState } from "@store/index";
import { persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";

// 搜索历史关键词对象类型
export interface SearchKey {
  id: string;
  name: string;
}

// 搜索历史关键词实体适配器
const searchKeyEntityAdaptor = createEntityAdapter<SearchKey>();

// 搜索历史关键词状态切片
const { reducer: searchKeyReducer, actions } = createSlice({
  name: "searchKey",
  initialState: searchKeyEntityAdaptor.getInitialState(),
  reducers: {
    // 添加搜索历史关键词
    addKey(state, action) {
      searchKeyEntityAdaptor.addOne(state, {
        name: action.payload.name,
        id: nanoid(),
      });
    },
    // 删除搜索历史关键词
    removeKey(state, action) {
      searchKeyEntityAdaptor.removeOne(state, action.payload.id);
    },
    // 清空搜索历史关键词
    clearKey(state) {
      searchKeyEntityAdaptor.removeAll(state);
    },
  },
});

// 导出搜索历史关键字状态选择器
export const searchKeySelectors = searchKeyEntityAdaptor.getSelectors<AppState>(
  (state) => state.searchKeyReducer
);

// 持久化
const persistSearchKeyReducer = persistReducer(
  { key: "searchKeyReducer", storage },
  searchKeyReducer
);

export default persistSearchKeyReducer;
export const { addKey, removeKey, clearKey } = actions;